//
//  TimeCaler.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/6/1.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "TimeCaler.h"

@interface TimeCaler ()

@property (nonatomic, readwrite, assign) int verCodeTime;

@end

@implementation TimeCaler

- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (void)initialize
{
    self.verCodeTime = 0;
}

- (void)resetVercode:(int)vercodeTime
{
    if (vercodeTime < 0)
    {
        return;
    }
    
    self.verCodeTime = vercodeTime;
}

- (void)waitGetCode
{
    _verCodeTime = TimeCaler_MaxTime;
    
    __block int timeout = _verCodeTime + 1;
    //获取全局队列
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //创建一个定时器，并将定时器的任务交给全局队列执行(并行，不会造成主线程阻塞)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    // 设置触发的间隔时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //1.0 * NSEC_PER_SEC  代表设置定时器触发的时间间隔为1s
    //0 * NSEC_PER_SEC    代表时间允许的误差是 0s
    
    //block内部 如果对当前对象的强引用属性修改 应该使用__weak typeof(self)weakSelf 修饰  避免循环调用
    __weak typeof(self)weakSelf = self;
    //设置定时器的触发事件
    dispatch_source_set_event_handler(timer, ^{
        //倒计时  刷新button上的title ，当倒计时时间为0时，结束倒计时
        //1. 每调用一次 时间-1s
        timeout --;
        
        weakSelf.verCodeTime = timeout;
        
        //2.对timeout进行判断时间是停止倒计时，还是修改button的title
        if (timeout <= 0)
        {
            dispatch_source_cancel(timer);
        }
        else
        {
        }
    });
    dispatch_resume(timer);
}

@end
